package com.springBoot.springBootSysCore.common.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.springBoot.springBootSysCore.common.StaticConfig;
import com.springBoot.springBootSysCore.modules.entity.system.SysRole;
import com.springBoot.springBootSysCore.modules.entity.system.SysUser;
import com.springBoot.springBootSysCore.modules.shiro.SystemAuthorizingRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用的工具类-用于定义一些应用级的常量和方法
 * @author timo
 */
public class SessionUtils {
	/**
	 * 获取shiro的subject对象
	 * @return
	 */
	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}
	/**
	 * 清楚授权缓存
	 */
	public static void clearAllCachedAuthorizationInfo(){
		RealmSecurityManager securityManager=(RealmSecurityManager) SecurityUtils.getSecurityManager();
		SystemAuthorizingRealm myReam = (SystemAuthorizingRealm) securityManager.getRealms().iterator().next();
	    myReam.clearAllCachedAuthorizationInfo();
	}
	
	/**
	 * 获取放在subject中的用户名
	 * @return
	 */
	public static String getUserAccount(){
			return SecurityUtils.getSubject().getPrincipals().toString();
	}
	
	/**
	 * 获取session 中的user对象
	 * @return
	 * @throws JsonProcessingException
	 */
	public static SysUser getSessionUser(){
		SysUser obj = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(StaticConfig.CURRENT_USER);
		return obj;
	}
	/**
	 * 设置session中的user对象
	 * @param user
	 */
	public static void setSessionUser(SysUser user){
		 SecurityUtils.getSubject().getSession().setAttribute(StaticConfig.CURRENT_USER, user);
		 setSessionObj(StaticConfig.CURRENT_USER_ID, user.getId());
		 //为了不让search查询时过滤掉,所以必须要不为空的字符串
		 String roleIds = "xx";
		 List<String> roleIdsList = new ArrayList<String>();
		 roleIdsList.add(".");
		 if(user.getDefalutRole()!=null){
//			 SysRole role = user.getDefalutRole();
		 }
		 setSessionObj(StaticConfig.STB_USER_DEPART_IDS,roleIds);
		 setSessionObj(StaticConfig.STB_USER_DEPART_LIST_IDS, roleIdsList);
		 
	}
	public static SysUser getSessionUser(String sid){
		return (SysUser)SecurityUtils.getSecurityManager().getSession(new DefaultSessionKey(sid)).getAttribute(StaticConfig.CURRENT_USER);
	}
	/**
	 * 获取session 中的user 的ID
	 * @return
	 */
	public static String getSessionUserId(){
		return String.valueOf(SecurityUtils.getSubject().getSession().getAttribute(StaticConfig.CURRENT_USER_ID));
	}
	/**
	 * 获取session中的对象
	 * @param key
	 * @return
	 */
	public static Object getSessionObj(String key){
		return SecurityUtils.getSubject().getSession().getAttribute(key);
	}
	/**
	 * 设置session中的对象
	 */
	public static void setSessionObj(String key,Object obj){
		 SecurityUtils.getSubject().getSession().setAttribute(key, obj);
	}

}
